package com.github.mall.common.services.impl;

import cn.hutool.core.lang.Dict;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.mall.common.constant.CommonConstants;
import com.github.mall.common.dao.UmsAdminDao;
import com.github.mall.common.entity.UmsAdminEntity;
import com.github.mall.common.entity.UmsPermissionEntity;
import com.github.mall.common.services.UmsAdminService;
import com.github.mall.common.services.UmsPermissionService;
import com.github.mall.common.services.UmsRoleService;
import com.github.mall.common.util.EntityUtils;
import com.github.mall.common.util.JwtTokenUtil;
import com.github.mall.common.util.PasswordUtil;
import lombok.AllArgsConstructor;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class UmsAdminServiceImpl  extends ServiceImpl<UmsAdminDao, UmsAdminEntity> implements UmsAdminService {
    private final UmsAdminDao umsAdminDao;
    private final UmsRoleService umsRoleService;
    private final UmsPermissionService umsPermissionService;
    /**
     * spring security 查找用户实例的服务类
     */
    private final UserDetailsService userDetailsService;



    @Override
    public UmsAdminEntity getAdminByUsername(String username) {
        UmsAdminEntity umsAdminEntity = new UmsAdminEntity();
        umsAdminEntity.setUsername(username);
        return umsAdminDao.selectOne(new QueryWrapper<>(umsAdminEntity));
    }

    @Override
    public List<UmsPermissionEntity> getPermissionList(String userId) {
        List<UmsPermissionEntity> umsPermissionEntityList = new ArrayList<UmsPermissionEntity>();
        umsRoleService
                .getUserRoleList(userId)
                .stream()
                .map(e -> umsPermissionService.getUserPermissionList(e.getId()))
                .collect(Collectors.toList())
                .forEach(umsPermissionEntityList::addAll);
        return umsPermissionEntityList;
    }

    @Override
    public UmsAdminEntity register(Dict umsAdminParam) {
        UmsAdminEntity umsAdminEntity = EntityUtils.mapToEntity(umsAdminParam, UmsAdminEntity.class);
        //判断用户名是否重复
//       int count =  umsAdminDao.selectCount(new QueryWrapper<>(umsAdminEntity));
       Dict param = new Dict();
       param.put("username",umsAdminEntity.getUsername());
       List<UmsAdminEntity> list = umsAdminDao.selectByMap(param);
        if (list.size() == 0){
            umsAdminEntity.setStatus(CommonConstants.UMS_ADMIN_STATUS);
            //对密码加密
            umsAdminEntity.setPassword(PasswordUtil.getPassword(umsAdminEntity.getUsername(),umsAdminEntity.getPassword()));
            int flag = umsAdminDao.insert(umsAdminEntity);
            if(flag != 0){
                return umsAdminEntity;
            }
        }
        return null;
    }

    @Override
    public String login(Dict param)  {
        UmsAdminEntity umsAdminEntity = EntityUtils.mapToEntity(param, UmsAdminEntity.class);
        UserDetails userDetails = userDetailsService.loadUserByUsername(umsAdminEntity.getUsername());
        if (!PasswordUtil.verifyPassword(userDetails.getUsername(), userDetails.getPassword(), umsAdminEntity.getPassword())) {
            throw new BadCredentialsException("密码不正确");
        }
        /**
         * 用户名密码认证
         * userrDetails
         * 用户密码
         * 权限
         */
        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authentication);
        //生成token
        String token = JwtTokenUtil.generateToken(userDetails);
        return token;
    }
}
